package com.cgy.utils.spider.handler;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * @author CHTK
 */
public class Downloads {
    /**
     * 下载
     * @param all
     * @param download
     */
    public static void loader(List<String> all, String download) {
        URL url;
        for (String href : all) {
            try {
                url = new URL(href);
            } catch (MalformedURLException e) {
               continue;
            }
            if(null != url) {
                //下在资源
                DataInputStream dataInputStream = null;
                FileOutputStream fileOutputStream = null;
                try {
                    dataInputStream = new DataInputStream(url.openStream());
                    fileOutputStream = new FileOutputStream(new File(getStrName(href)));
                    byte[] bytes = new byte[1024];
                    int length = 0;
                    while ((length = dataInputStream.read(bytes)) != -1) {
                        fileOutputStream.write(bytes, 0, length);
                        System.out.println("下载中....");
                    }
                    System.out.println("下载完成...");
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    try {
                        dataInputStream.close();
                    } catch (IOException e) {
                    }
                    try {
                        fileOutputStream.close();
                    } catch (IOException e) {
                    }
                }
            }
        }
    }


    private static String getStrName(String url) {
        String[] sarry = url.split("/");
        return sarry[sarry.length - 1];
    }
}
